package com.farm.wcp.api.controller;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.farm.core.page.ViewMode;
import com.farm.file.WdapFileServiceInter;
import com.farm.file.domain.FileBase;
import com.farm.file.domain.FileText;
import com.farm.file.domain.ex.FileView;
import com.farm.file.domain.ex.PersistFile;
import com.farm.file.service.FileBaseServiceInter;
import com.farm.file.service.FileTextServiceInter;
import com.farm.view.domain.ViewConvertor;
import com.farm.view.domain.ViewFileModel;
import com.farm.view.domain.ViewLog;
import com.farm.view.domain.ViewTask;
import com.farm.view.service.ViewConvertorServiceInter;
import com.farm.view.service.ViewDocServiceInter;
import com.farm.view.service.ViewFileModelServiceInter;
import com.farm.view.service.ViewLogServiceInter;
import com.farm.view.service.ViewTaskServiceInter;
import com.farm.wcp.util.DownloadUtils;
import com.farm.wcp.util.ThemesUtil;
import com.farm.web.WebUtils;

/**
 * 引用组件页面
 * 
 * @author autoCode
 * 
 */
@RequestMapping("/include")
@Controller
public class OutIncludeController extends WebUtils {
	private static final Logger log = Logger.getLogger(OutIncludeController.class);
	@Resource
	private WdapFileServiceInter wdapFileServiceImpl;
	@Resource
	private FileBaseServiceInter fileBaseServiceImpl;
	@Resource
	private ViewTaskServiceInter viewTaskServiceImpl;
	@Resource
	private ViewDocServiceInter viewDocServiceImpl;
	@Resource
	private ViewLogServiceInter viewLogServiceImpl;
	@Resource
	private ViewFileModelServiceInter viewModelServiceImpl;
	@Resource
	private ViewConvertorServiceInter viewConvertorServiceImpl;
	@Resource
	private FileTextServiceInter fileTextServiceImpl;

	@RequestMapping("/Pubview")
	public ModelAndView pview(String fileid, HttpServletRequest request, HttpSession session) {
		try {
			ViewMode view = ViewMode.getInstance();
			List<Map<String, Object>> viewDocs = viewDocServiceImpl.getFileViewdocs(fileid);
			view.putAttr("viewdocs", viewDocs);
			FileText text = fileTextServiceImpl.getFiletextByFileId(fileid);
			view.putAttr("filetext", text);
			String onlyUrl = null;
			for (Map<String, Object> node : viewDocs) {
				if (node.get("VIEWIS").equals("1") && StringUtils.isNotBlank(node.get("VIEWURL").toString())) {
					if (onlyUrl == null) {
						onlyUrl = node.get("VIEWURL").toString();
					} else {
						onlyUrl = null;
						break;
					}
				}
			}
			if (viewDocs.size() > 0) {
				if (onlyUrl == null) {
					// 多个预览资源
					return view.returnModelAndView("/web-simple/outview/view");
				} else {
					// 就一个预览资源
					return view.returnRedirectUrl("/" + onlyUrl);
				}
			} else {
				List<Map<String, Object>> viewTasks = viewTaskServiceImpl.getTasksByFileid(fileid);
				FileBase fileBase =	wdapFileServiceImpl.getFileBase(fileid);
				view.putAttr("viewtasks", viewTasks);
				view.putAttr("fileid",fileid);
				view.putAttr("secret",fileBase.getSecret());
				return view.returnModelAndView("/web-simple/outview/viewWait");
			}
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePage("error-sys"));
		}
	}

	@RequestMapping("/Pubtasks")
	public ModelAndView plogs(String fileid, HttpServletRequest request, HttpSession session) {
		try {
			ViewMode view = ViewMode.getInstance();
			FileView fileview = fileBaseServiceImpl.getFileView(fileid);
			view.putAttr("fileview", fileview);
			List<Map<String, Object>> viewTasks = viewTaskServiceImpl.getTasksByFileid(fileid);
			view.putAttr("viewtasks", viewTasks);
			FileText text = fileTextServiceImpl.getFiletextByFileId(fileid);
			view.putAttr("filetext", text);
			return view.returnModelAndView("/web-simple/outview/tasklist");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePage("error-sys"));
		}
	}

	@RequestMapping("/Publog")
	public ModelAndView publog(String taskid, HttpServletRequest request, HttpSession session) {
		try {
			////////// -!!!!!!!!!!!!!!!!未完成，要实现在界面点击查看任务信息时展示，任务信息以及任务的日志信息.
			ViewMode view = ViewMode.getInstance();
			ViewTask task = viewTaskServiceImpl.getViewtaskEntity(taskid);
			List<ViewLog> logs = viewLogServiceImpl.getlogsByTaskid(task.getId());
			FileView fileview = fileBaseServiceImpl.getFileView(task.getFileid());
			ViewConvertor convertor = viewConvertorServiceImpl.getViewconvertorEntity(task.getConvertorid());
			ViewFileModel tmodel = viewModelServiceImpl.getViewmodelEntity(convertor.getTmodelid());
			ViewFileModel omodel = viewModelServiceImpl.getViewmodelEntity(convertor.getOmodelid());
			view.putAttr("tmodel", tmodel);
			view.putAttr("omodel", omodel);
			view.putAttr("convertor", convertor);
			view.putAttr("fileview", fileview);
			view.putAttr("task", task);
			view.putAttr("logs", logs);
			return view.returnModelAndView("/web-simple/outview/taskLog");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePage("error-sys"));
		}
	}

	/**
	 * 下載文件(普通下载)
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	@RequestMapping("/Pubdown")
	public void Pubdown(String id, String secret, HttpServletRequest request, HttpServletResponse response)
			throws FileNotFoundException, IOException {
		PersistFile file = wdapFileServiceImpl.getPersistFile(id);
		if (!file.getSecret().trim().equals(secret)) {
			response.sendError(405, "安全码错误!secret：" + secret);
			return;
		}
		wdapFileServiceImpl.downloadFileHandle(id);
		DownloadUtils.downloadFile(file.getFile(), file.getName(), response);
	}
}
